package com.zr.bookcorner.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.model.BookModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.ListUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.cabinet.UserInfo;
import com.zh.model.request.ErrorInfo;
import com.zh.model.request.LoginInfo;
import com.zr.andealib.util.CheckBookMediumUtil;
import com.zr.andealib.util.CheckBookUtil;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.LockUtil;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.andealib.util.constant.CheckUtil;
import com.zr.andealib.util.model.InventoryReport;
import com.zr.bookcorner.BookApplication;
import com.zr.bookcorner.constant.Constant;
import com.zr.bookcorner.presenter.view.ChooseView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

public class ChoosePresenter extends BasePresenter<ChooseView> {
    private BookModel bookModel;
    private LockUtil lockUtil;
    private int boxNum;
    private int boxNumCheck;
    private String uid;
    private String lastType;
    private int type;
    private boolean hasCount = false;

    @Override
    public void attachModel(Context context) {
        bookModel = new BookModel(context);
        uid = ShareManager.getValue(getContext(), Constant.LAST_USER_ID);
        lastType = ShareManager.getValue(getContext(), Constant.LAST_USER_TYPE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        boxNumCheck = ShareManager.getInt(getContext(), Constant.LAST_OPEN);
        LogUtils.e("boxNumCheck:" + boxNumCheck);
        if (boxNumCheck != 0) {
            //盘点然后调用提交功能
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CheckUtil mCheckBookUtil;
                    if (BookApplication.isBig())
                        mCheckBookUtil = new CheckBookMediumUtil();
                    else
                        mCheckBookUtil = new CheckBookUtil();
                    mCheckBookUtil.init();
                    mCheckBookUtil.bookGridIdInventory(boxNumCheck);
                    mCheckBookUtil.destory();
                }
            }).start();
        }

    }

    public void setType(int type) {
        this.type = type;
    }

    public void initLock() {
        if (lockUtil == null) {
            lockUtil = new LockUtil();
            lockUtil.init();
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    public void onDestroy() {
        if (lockUtil != null) {
            lockUtil.destory();
            lockUtil = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void checkDoorStatus(int boxNum) {
        this.boxNum = boxNum;
        if (lockUtil.isDoorOPen(boxNum)) {
            ToastView.showLong("当前柜门开启，请先关闭");
        } else {
            getView().showDialog();
        }
    }

    public void open(int boxNum) {
        lockUtil.openDoor(boxNum);
    }

    private void checkCard(String cardCode) {
        String uuid = PhoneUtil.getUUID(getContext());
        String schoolId = ShareManager.getValue(getContext(), BaseConstant.DEVICE_SCHOOL_ID);
        Observable<BaseResp<UserInfo>> observable = getObservableNotFilter(bookModel.login(schoolId, new LoginInfo(cardCode, uuid, type)));
        observable.subscribe(new RxSubscribe<BaseResp<UserInfo>>() {
            @Override
            public void onSuccess(BaseResp<UserInfo> userInfoBaseResp) throws Exception {
                if (userInfoBaseResp.getCode() == 0) {
                    UserInfo info = userInfoBaseResp.getData();
                    ShareManager.setValue(getContext(), BaseConstant.TOKEN_ID,
                            info.getToken());
                    ShareManager.setValue(getContext(), Constant.LAST_USER_ID,
                            info.getId() + "");
                    ShareManager.setValue(getContext(), Constant.LAST_USER_TYPE,
                            info.getType() + "");
                    lockUtil.openDoor(boxNum);
                    ShareManager.setInt(getContext(), Constant.LAST_OPEN, boxNum);
                    getView().onSuccess(null);
                } else {
                    getView().defyError();
                    ToastView.showLong(userInfoBaseResp.getMsg());
                }
            }

            @Override
            public void onHint(String hint) {
                getView().onHint(hint);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_VERIFICATION_SUCCSES) {  //磁卡登录
            String code = (String) hardEvent.getData();
            checkCard(code);
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            int type = lockUtil.readLock(boxNum);
            if (type == 0)
                getView().openSuccess();
            else
                getView().openError();

        } else if (flag == AndeaConstant.CALL_INIT_VERIFICATION_ERROR || flag == AndeaConstant.CALL_LOCK_STATUS_ERROR) {
            String msg = (String) hardEvent.getData();
            ToastView.showLong(msg);
            if (!msg.equals("柜门处于开启状态")) {
                getView().openError();
            }
        } else if (flag == AndeaConstant.CALL_INIT_CHECK_ERROR || flag == AndeaConstant.CALL_READ_CHECK_ERROR) {
            String msg = (String) hardEvent.getData();
            ToastView.showLong(msg);
        } else if (flag == AndeaConstant.CALL_READ_CHECK_SUCCSES) {
            List<InventoryReport> listTags = (List<InventoryReport>) hardEvent.getData();
            ShareManager.setInt(getContext(), Constant.LAST_OPEN, 0);
            doCheck(listTags);
        }
    }

    private void doCheck(List<InventoryReport> listTags) {
        String all = ShareManager.getValue(getContext(), Constant.BOX_DATA + boxNumCheck);
        List<String> oldTag = null;
        if (!TextUtils.isEmpty(all))
            oldTag = JsonUtils.stringToList(all, String.class);
        List<String> listTag = new ArrayList<>();
        for (InventoryReport tag : listTags) {
            listTag.add(tag.getUidStr());
        }
        if (ListUtils.isEmpty(oldTag)) {
            ShareManager.setValue(getContext(), Constant.BOX_DATA + boxNumCheck, JsonUtils.objectToString(listTag));
        } else {
            List<String> cacheTags = JsonUtils.stringToList(all, String.class);
            cacheTags.removeAll(listTag);
            if (!ListUtils.isEmpty(cacheTags)) {
                error(boxNumCheck, listTag, cacheTags);
            }
        }
    }

    private void error(int errorNum, List<String> now, List<String> list) {
        String schoolId = ShareManager.getValue(getContext(), BaseConstant.DEVICE_SCHOOL_ID);
        Observable<BaseResp<Object>> observable = getObservableNotStop(bookModel.error(schoolId, new ErrorInfo(uid, list, Integer.parseInt(lastType))));
        observable.subscribe(new RxSubscribe<BaseResp<Object>>() {
            @Override
            public void onSuccess(BaseResp<Object> objectBaseResp) throws Exception {
                ShareManager.setValue(getContext(), Constant.BOX_DATA + errorNum, JsonUtils.objectToString(now));
            }

            @Override
            public void onHint(String hint) {
                getView().onHint(hint);
            }
        });
    }

    public void count() {
        if (hasCount)
            return;
        hasCount = true;
        bookModel.selectCount(ShareManager.getValue(getContext(), BaseConstant.DEVICE_SCHOOL_ID))
                .subscribeOn(Schedulers.io())//启动订阅线程
                .subscribe(new RxSubscribe<BaseResp<Object>>() {
                    @Override
                    public void onSuccess(BaseResp<Object> listBaseResp) throws Exception {
                    }

                    @Override
                    public void onHint(String hint) {

                    }
                });
    }
}
